<?php

namespace Serve\Controller;

use Common\Controller\NormalApiController;

class PasswordController extends NormalApiController
{
    public function __construct()
    {
        parent::__construct();
    }

    public function change()
    {
        if ($this->_method == 'options') {
            $this->options('Access-Control-Allow-Methods: POST, OPTIONS');
        }
        $username = $this->_request['username'];
        $password = $this->_request['password'];
        $newPassword = $this->_request['newPassword'];
        if (!$username || !$password || !$newPassword)
            ClientError('缺少参数', C('CODE.BAD_REQUEST')['code']);
        //$model = $this->_db->users;
        $cond = ['auth' => ['username' => $username, 'password' => md5($password)]];
        if ($userInfo = $this->checkAuth($this->_db->users, $cond)) {
            Success(200, $this->_db->users->auth->update($userInfo['userId'], ['username' => $username, 'password' => md5($newPassword)]));
        } else
            ClientError('用户密码错误', C('CODE.NOT_FOUND')['code']);
    }

    private function checkAuth($model, $cond)
    {
        $result = [];
        if ($user = $model->findUnique($cond)) {
            $result['userId'] = $user['id'];
            $result['username'] = $user['auth']['username'];
            $result['role'] = $user['role'];
        }
        return $result;
    }
}